package com.dengpp.pdform.holder;


import android.os.Build;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import androidx.annotation.NonNull;
import com.dengpp.pdform.R;
import com.dengpp.pdform.adapter.AttributeAdapter;
import com.dengpp.pdform.base.BaseAttributeViewHolder;
import com.dengpp.pdform.config.AttributeConfig;
import java.util.ArrayList;
import java.util.List;
import android.graphics.drawable.GradientDrawable;
import android.view.ViewGroup;
import com.google.android.flexbox.FlexboxLayout;


public class CheckboxViewHolder extends BaseAttributeViewHolder {
    private TextView tvTitle;
    private FlexboxLayout flexboxLayout;
    private TextView tvValue;
    private List<String> selectedValues;
    private List<String> options;

    public CheckboxViewHolder(@NonNull View itemView) {
        super(itemView);
        tvTitle = itemView.findViewById(R.id.tv_title);
        flexboxLayout = itemView.findViewById(R.id.flexbox_layout);
        tvValue = itemView.findViewById(R.id.tv_value);
    }

    @Override
    @SuppressWarnings("unchecked")
    public void bind(AttributeConfig attribute, boolean isEditMode, AttributeAdapter.OnAttributeChangeListener listener) {
        // 使用带星号的标题
        tvTitle.setText(getTitleWithRequiredStar(attribute.getTitle(), attribute.isRequired()));
        this.options = attribute.getOptions();
        this.selectedValues = attribute.getValue() instanceof List ?
                new ArrayList<>((List<String>) attribute.getValue()) : new ArrayList<>();

        if (isEditMode && attribute.isEditable()) {
            flexboxLayout.setVisibility(View.VISIBLE);
            tvValue.setVisibility(View.GONE);

            // 清除之前的选项
            flexboxLayout.removeAllViews();

            if (options != null) {
                for (String option : options) {
                    boolean isSelected = selectedValues.contains(option);
                    CheckBox checkBox = createCheckBox(option, isSelected);
                    checkBox.setTag(option); // 使用tag存储选项值

                    // 设置点击监听器
                    checkBox.setOnClickListener(v -> {
                        String optionValue = (String) v.getTag();
                        CheckBox cb = (CheckBox) v;

                        if (cb.isChecked()) {
                            if (!selectedValues.contains(optionValue)) {
                                selectedValues.add(optionValue);
                            }
                        } else {
                            selectedValues.remove(optionValue);
                        }

                        // 更新按钮外观
                        updateCheckBoxAppearance(cb, cb.isChecked());

                        // 通知监听器
                        if (listener != null) {
                            listener.onAttributeChanged(attribute.getKey(), new ArrayList<>(selectedValues));
                        }
                    });

                    flexboxLayout.addView(checkBox);
                }
            }

        } else {
            flexboxLayout.setVisibility(View.GONE);
            tvValue.setVisibility(View.VISIBLE);

            if (!selectedValues.isEmpty()) {
                tvValue.setText(String.join(", ", selectedValues));
            } else {
                tvValue.setText(attribute.getValue() != null ? attribute.getValue().toString() : "");
            }
        }
    }
    /**
     * 在 ViewHolder 被回收时清理资源
     */
    @Override
    public void onViewRecycled() {
        super.onViewRecycled();
        // 移除所有多选按钮的点击监听器
        for (int i = 0; i < flexboxLayout.getChildCount(); i++) {
            View child = flexboxLayout.getChildAt(i);
            if (child instanceof CheckBox) {
                child.setOnClickListener(null);
            }
        }
    }
    private CheckBox createCheckBox(String text, boolean isChecked) {
        CheckBox checkBox = new CheckBox(itemView.getContext());

        // 设置布局参数
        FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
        );
        layoutParams.setMargins(0, 0, 16, 8);
        checkBox.setLayoutParams(layoutParams);

        // 设置文本和状态
        checkBox.setText(text);
        checkBox.setChecked(isChecked);
        checkBox.setTextSize(14);
        checkBox.setPadding(24, 12, 24, 12);

        // 移除默认按钮
        checkBox.setButtonDrawable(null);

        // 设置选中状态和样式
        updateCheckBoxAppearance(checkBox, isChecked);

        return checkBox;
    }

    private void updateCheckBoxAppearance(CheckBox checkBox, boolean isChecked) {
        GradientDrawable background = new GradientDrawable();
        background.setShape(GradientDrawable.RECTANGLE);
        background.setCornerRadius(20);

        if (isChecked) {
            background.setColor(itemView.getContext().getResources().getColor(R.color.library_colorPrimary));
            background.setStroke(2, itemView.getContext().getResources().getColor(R.color.library_colorPrimary));
            checkBox.setTextColor(itemView.getContext().getResources().getColor(R.color.library_white));
        } else {
            background.setColor(itemView.getContext().getResources().getColor(R.color.library_white));
            background.setStroke(2, itemView.getContext().getResources().getColor(R.color.library_gray_light));
            checkBox.setTextColor(itemView.getContext().getResources().getColor(R.color.library_gray_dark));
        }

        checkBox.setBackground(background);
    }
}